package com.zhangyj.impl.actions;

import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.type.TypeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhangyj.BoastException;
import com.zhangyj.action.AbstractAction;
import com.zhangyj.action.RequestAction;
import com.zhangyj.action.RequestMethod;
import com.zhangyj.action.ResponseResultType;
import com.zhangyj.dao.DaoManager;
import com.zhangyj.dao.MenuAndTreeDao;
import com.zhangyj.dao.ProgramDao;
import com.zhangyj.db.DBUtil;
import com.zhangyj.entitis.Menutree;
import com.zhangyj.entitis.Program;
import com.zhangyj.entitis.Role;
import com.zhangyj.entitis.TreeItem;
import com.zhangyj.impl.UserContext;
import com.zhangyj.impl.ViewName;
import com.zhangyj.impl.plugin.IDataService;
import com.zhangyj.impl.plugin.JSONClientDataService;
import com.zhangyj.security.Permission;
import com.zhangyj.util.OutlookBarCreator;
import com.zhangyj.util.Tools;
@RequestAction(name="function")
public class FunctionAction extends AbstractAction {
	private static Logger logger = LoggerFactory.getLogger(FunctionAction.class);

	private static final long serialVersionUID = 2984461775661183586L;

	@RequestMethod(name = "load", result = ResponseResultType.PATH)
	public String onload() throws Exception {
		try {
			List<TreeItem> list = getFunctionList();
			OutlookBarCreator outlookBarCreator = new OutlookBarCreator(list, request.getContextPath());
			request.setAttribute("outlookbar", outlookBarCreator);
			return ViewName.FUNCTIONS;
		} catch (Exception e) {
			throw new BoastException(e);
		}
	}

	// private String onloadAccordion() throws Exception {
	// try {
	// List<TreeItem> list = getFunctionList();
	// AccordionCreator outlookBarCreator = new AccordionCreator(list,
	// request.getContextPath());
	// request.setAttribute("outlookbar", outlookBarCreator);
	// return ViewName.FUNCTIONS;
	// } catch (Exception e) {
	// throw new BoastException(e);
	// }
	// }
	private List<TreeItem> getFunctionList() throws Exception {
		List<TreeItem> returnlist = new ArrayList<TreeItem>();
		MenuAndTreeDao matd = DaoManager.getDao(MenuAndTreeDao.class);
		UserContext userContext = UserContext.getUserContext(request);
		Set<Integer> set = matd.getProgramIdSet(userContext.getUserid());
		int templateId = matd.getMenuTemplateId(userContext.getUserid(), userContext.getEntid());
		List<?> list = matd.getTreeItemList(templateId);
		for (Iterator<?> iter = list.iterator(); iter.hasNext();) {
			Menutree mt = (Menutree) iter.next();
			TreeItem item = new TreeItem(0, mt.getProgramid(), mt.getCatcode(), mt.getMenuname(), true);
			if (item.getId() < 1) {
				item.setLeaf(true);
				returnlist.add(item);
				continue;
			}
			if (set.contains(item.getId())) {
				item.setLeaf(true);
				returnlist.add(item);
			} else {
				item.setLeaf(false);
			}
		}
		return returnlist;
	}

	@RequestMethod(name = "saveFunc")
	public String saveFunc() throws Exception {
		String oper = this.getParameter("oper");
		Program info = new Program();
		Tools.fullBean(info, request);
		int id = -1;
		MenuAndTreeDao matd = DaoManager.getDao(MenuAndTreeDao.class);
		if ("add".equals(oper)) {
			id = DBUtil.getIntId("programlist");
		} else {
			id = this.getIntParameter("programid");
		}
		info.setProgramid(id);
		if ("add".equals(oper)) {
			matd.saveProgramInfo(info, true);
		} else if ("edit".equals(oper)) {
			matd.saveProgramInfo(info, false);
		} else if ("del".equals(oper)) {
			matd.delProgram(id);
		}
		response.setContentType("application/json;charset=UTF-8");
		Tools.formSuccess(response.getWriter(), "", info);
		return null;
	}

	@RequestMethod(name = "permission")
	public void permission() throws Exception {
		response.setContentType("text/xml;charset=UTF-8");
		int id = this.getIntParameter("programid");
		ProgramDao pd = DaoManager.getDao(ProgramDao.class);
		List<Role> list = pd.getProgramRoles(id);
		List<Object[]> list1 = new ArrayList<Object[]>();
		Iterator<Role> iter = list.iterator();
		while (iter.hasNext()) {
			Role role = iter.next();
			Object[] vals = new Object[7];
			vals[0] = role.getRoleid();
			vals[1] = role.getRolename();
			vals[2] = (role.getOption_permission() & Permission.VIEW) == Permission.VIEW;
			vals[3] = (role.getOption_permission() & Permission.ADD) == Permission.ADD;
			vals[4] = (role.getOption_permission() & Permission.UPDATE) == Permission.UPDATE;
			vals[5] = (role.getOption_permission() & Permission.DELETE) == Permission.DELETE;
			vals[6] = id;
			list1.add(vals);
		}
		IDataService ids = new JSONClientDataService(list1, new String[] { "roleid", "rolename", "view", "add", "edit", "del", "programid" });
		ids.open();
		Writer writer = response.getWriter();
		ids.writerTo(writer);
		ids.close();
	}

	@RequestMethod(name = "savePermission")
	public void savePermission() throws Exception {
		logger.debug("保存权限开始...");
		String json = getParameter("json");
		int programid = -1;
		List<Map<String, Object>> list = Tools.jsonStr2object(json, TypeFactory.collectionType(ArrayList.class, TypeFactory.mapType(HashMap.class, String.class, Object.class)));
		List<Role> roles = new ArrayList<Role>();
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> map = iter.next();
			programid = (Integer) map.get("programid");
			int permission = 0;
			if ((Boolean) map.get("view")) {
				permission = permission | Permission.VIEW;
			}
			if ((Boolean) map.get("edit")) {
				permission = permission | Permission.UPDATE;
			}
			if ((Boolean) map.get("add")) {
				permission = permission | Permission.ADD;
			}
			if ((Boolean) map.get("del")) {
				permission = permission | Permission.DELETE;
			}
			if (permission == 0) {
				continue;
			}
			Role role = new Role();
			role.setRoleid(Integer.valueOf(map.get("roleid").toString()));
			role.setOption_permission(permission);
			roles.add(role);
		}
		ProgramDao pd = DaoManager.getDao(ProgramDao.class);
		pd.saveProgramRoles(programid, roles);
		logger.debug("保存权限结束...");
	}

	public static void main(String[] args) {
		System.out.println(1 | 4);
	}
}
